package com.zhentao.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.aop.MyLog;
import com.zhentao.domain.*;
import com.zhentao.dto.ClassTuserDto;
import com.zhentao.dto.QuestionDto;
import com.zhentao.dto.SubjectDto;
import com.zhentao.dto.WordReturn;
import com.zhentao.result.Result;
import com.zhentao.service.*;
import com.zhentao.service.impl.FeginServiceImpl;
import com.zhentao.service.impl.FileWordServiceImpl;
import com.zhentao.service.impl.WordDocumentService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("question")
public class QuestionController {
    @Resource
    private SQuestionService sQuestionService;
    @Resource
    private SLevelService sLevelService;
    @Resource
    private SSubjectService sSubjectService;
    @Resource
    private FileWordServiceImpl fileWordService;
    @Resource
    private STypeService sTypeService;
    @Resource
    private FeginServiceImpl feginService;
    @Resource
    private SErrorBookService sErrorBookService;
    @Resource
    private SLearningProgressService sLearningProgressService;

    @PostMapping("questionDelete")
    public Result questionDelete(Integer qid){
        sQuestionService.removeById(qid);
        return Result.OK();
    }

    @PostMapping("findAllQuestion")
    public Result findAllQuestion(@RequestBody QuestionDto questionDto){
       return sQuestionService.findAllQuestion(questionDto);
    }
    @PostMapping("questionUpdate")
    @MyLog(title = "题库模块",content = "修改或添加题目")
    public Result questionUpdate(@RequestBody SQuestion sQuestion){
        if (sQuestion.getQuestion() == null||sQuestion.getQuestion().equals("")) {
            return Result.ERROR("题干不能为空");
        }
        if (sQuestion.getAnswerTxt() == null||sQuestion.getAnswerTxt().equals("")) {
            return Result.ERROR("答案不能为空");
        }
        if (sQuestion.getTypeId() == null||sQuestion.getTypeId()==0) {
            return Result.ERROR("类型不能为空");
        }
        Integer aa=0;
        if (sQuestion.getId()==null) {
            List<SQuestion> list = sQuestionService.list(Wrappers.<SQuestion>lambdaQuery().eq(SQuestion::getSubId, sQuestion.getSubId()));
            for (SQuestion question : list) {
                if (sQuestion.getQuestion().equals(question)) {
                    aa++;
                }
            }
        }
        if (aa == 1) {
            return Result.ERROR("题已经重复");
        }
        sQuestionService.saveOrUpdate(sQuestion);
        return Result.OK();
    }
    //查看阶段
    @GetMapping("findAllLevel")
    public Result findAllLevel(){
        List<SLevel> allLevel = sLevelService.list();
        for (SLevel sLevel : allLevel) {
            List<SLearningProgress> list = sLearningProgressService.list(Wrappers.<SLearningProgress>lambdaQuery().eq(SLearningProgress::getLevelId, sLevel.getId()));
            sLevel.setSLearningProgress(list);
            for (SLearningProgress sLearningProgress : list) {
                List<SSubject> list1 = sSubjectService.list(Wrappers.<SSubject>lambdaQuery().eq(SSubject::getLpId, sLearningProgress.getId()));
                sLearningProgress.setSSubjects(list1);
            }
        }
        return Result.OK(allLevel);
    }
    //word文档批量添加
    @PostMapping("UploadQuestion")
    @MyLog(title = "题库模块", content = "批量添加题目")
    public Result UploadQuestion(MultipartFile file){
        try {
            fileWordService.UploadQuestion(file);
        }catch (Exception exception){
            return Result.ERROR("模板格式不正确");
        }

        return Result.OK(file.getOriginalFilename());
    }
    //查看所有题型
    @MyLog(title = "题库模块", content = "查看全部题型")
    @GetMapping("findAllType")
    public Result findAllType(){
        return Result.OK(sTypeService.list());
    }

    @GetMapping("findUserSub")
    public Result  findUserSub(Integer uid){
        List<SubjectDto> userSub = sSubjectService.findUserSub(uid);
        return Result.OK(userSub);
    }
    @Resource
    private SClassService sClassService;
    @Resource
    private SAnswerService sAnswerService;
    @Resource
    private WordDocumentService wordDocumentService;

    //查找挡板讲师的学生信息（条件查询学生姓名，班级名称，阶段id）
    @PostMapping("findTeacherSubject")
    public Result findTeacherSubject(@RequestBody ClassTuserDto classTuserDto){
        PageHelper.startPage(classTuserDto.getPageNum(), classTuserDto.getPageSize());
        List<ClassTuserDto> teacherSubject = sQuestionService.findTeacherSubject(classTuserDto);
        PageInfo<ClassTuserDto> classTuserDtoPageInfo = new PageInfo<>(teacherSubject);
        return Result.OK(classTuserDtoPageInfo);
    }
    //查找全部学科的课程
    @GetMapping("findAllSub")
    public Result findAllSub(){
        List<SSubject> list = sSubjectService.list();
        return Result.OK(list);
    }
    //查找全部班级
    @GetMapping("findAllClass")
    public Result findAllClass(){
        List<SClass> list = sClassService.list();
        return Result.OK(list);
    }
    //通过学生查找个人成绩(条件查询考试)
    @GetMapping("getPersonalMerit")
    public Result getPersonalMerit(Integer uid,Integer testinfoId){
        if (testinfoId != null) {
            List<SAnswer> list = sAnswerService.list(Wrappers.<SAnswer>lambdaQuery().eq(SAnswer::getUId, uid).eq(SAnswer::getTestinfoId,testinfoId));
            return Result.OK(list);
        }else {
            List<SAnswer> list = sAnswerService.list(Wrappers.<SAnswer>lambdaQuery().eq(SAnswer::getUId, uid));
            return Result.OK(list);
        }
    }
    //添加考试
    @GetMapping("/addExaminationInformation")
    @MyLog(title = "题库模块",content = "模拟考试")
    public Result addExaminationInformation(Integer subId){
        return feginService.addExaminationInformation(subId);
    }
    //通过学科查看题目
    @GetMapping("/findQuestionBySub")
    public Result findQuestionBySub(int pageNum,int pageSize,Integer subId){
        PageHelper.startPage(pageNum, pageSize);
        List<SQuestion> list = sQuestionService.list(Wrappers.<SQuestion>lambdaQuery().eq(SQuestion::getSubId, subId));
        PageInfo<SQuestion> sQuestionPageInfo = new PageInfo<>(list);
        return Result.OK(sQuestionPageInfo);
    }
    //word文档导出
    @PostMapping ("/download-word")
    @MyLog(title = "题库模块", content = "导出word文档")
    public ResponseEntity<org.springframework.core.io.Resource> downloadWordDocument(@RequestBody QuestionDto questionDto) throws IOException {
//        questionDto.setSubId(2);
        List<SQuestion> allQuestions = sQuestionService.findAllQuestions(questionDto);
        return wordDocumentService.generateWordDocument(allQuestions);
    }

    /**
     * 导出word模板
     * @return
     * @throws IOException
     */
    @PostMapping ("/outQuestionOne")
    public ResponseEntity<org.springframework.core.io.Resource> outQuestionOne() throws IOException {
        List<SQuestion> allQuestions = sQuestionService.getModel();
        return wordDocumentService.generateWordDocument(allQuestions);
    }


    //查询单个试题
    @PostMapping("findOneError")
    public Result findOneError(@RequestBody QuestionDto questionDto) {
        return Result.OK(sQuestionService.findOneError(questionDto));
    }
    //查询用户的个人试题
    @PostMapping("findAllError")
    public Result findAllError(Integer uid) {
        return Result.OK(sQuestionService.findAllError(uid));
    }
    //新增错题
    @PostMapping("addError")
    @MyLog(title = "题库模块", content = "新增错题")
    public Result addError(@RequestBody QuestionDto questionDto) {
        SErrorBook one = sErrorBookService.getOne(Wrappers.<SErrorBook>lambdaQuery().eq(SErrorBook::getQuestionId, questionDto.getQid()).eq(SErrorBook::getUserId, questionDto.getUid()));
        if (one==null){
            SErrorBook sErrorBook = new SErrorBook();
            sErrorBook.setQuestionId(questionDto.getQid());
            sErrorBook.setUserId(questionDto.getUid());
            sErrorBookService.save(sErrorBook);
            return Result.OK();
        }else {
            return Result.ERROR("请不要重复添加错题哦！");
        }
    }
    @GetMapping("redisToMysql")
    @MyLog(title = "题库模块", content = "导入word文档")
    public Result redisToMysql(String fileName,Integer subId){
        WordReturn wordReturn = fileWordService.redisToMysql(fileName, subId);
        wordReturn.setFileName(fileName);
        return Result.OK(wordReturn);
    }
    /**
     * 导出word模板
     * @return
     * @throws IOException
     */
    @PostMapping ("/outQuestionOne")
    public ResponseEntity<org.springframework.core.io.Resource> outQuestionOne() throws IOException {
        List<SQuestion> allQuestions = sQuestionService.getModel();
        return wordDocumentService.generateWordDocument(allQuestions);
    }

}
